<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\admin\controller;
use app\admin\model\Admintype;
use app\admin\model\Campus;
use app\admin\validate\AdminValidate;
use think\Db;
use app\admin\model\Admin;

class ApigroupController extends CommonController
{
    /**
     * 创建群
     * 参数：1、uid(必须是数组且包含创建人id：要加入这个群的用户id），2、name：群名字，3、thumb：群头像，4、notice：群公告
     * @return string
     */
    public function createGroup(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $num = Db::table('ew_group')
            ->where('g_user_id',$user_id)
            ->where('g_status',1)
            ->count();
        if($num >= 3){
            return json_encode(['status'=>0,'msg'=>'您已创建了三个群，已达上限']);
        }
		$uid = json_decode($uid,true);
		
        if(!$uid){
            return json_encode(['status'=>0,'msg'=>'请选择用户']);
        }
        $uidArray = $uid;
        $uid = implode($uid,',');
        $uid = trim($uid,',');
        $uid = ',' . $uid . ',';
        $data = array();
        $data['g_name'] = $name;
        $data['g_id'] = $this->uuid();
        $data['g_user_id'] = $user_id;
        $data['g_uids'] = $uid;
        $data['g_notice'] = $notice;
        $data['g_thumb'] = $thumb;
        Db::startTrans();
        try {
            $groupid = $data['g_id'];
            Db::table('ew_group')->insert($data);
            $uids = '';
            foreach ($uidArray as $v) {
                $uids .= "userId={$v}&";
            }

            $res = $this->create($uids,$groupid,$name);

            if ($res['code'] != 200) {
                Db::table('ew_group')->where('g_id', $groupid)->delete();
                $status = 0;
                $msg = '新增失败';
            }else{
                $status = 200;
                $msg = '成功';
            }
            Db::commit();
            $returnData['status'] = $status;
            $returnData['msg'] = $msg;
            return json_encode($returnData);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $returnData['status'] = 0;
            $returnData['msg'] = "新增失败！";
            return json_encode($returnData);
        }
    }

    /**
     * 加入群组：加人
     * 参数：1、uid(必须是数组：要加入的这些人的id)，2、群id
     * @return string
     */
    public function joinGroup(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $g = Db::table('ew_group')->where('g_id', $groupid)->find();
        $g['g_uids'] = trim($g['g_uids'],',');
        $uids = explode(',',$g['g_uids']);
        $uid = json_decode($uid,true);
        if(!$uid){
            return json_encode(['status'=>0,'msg'=>'请选择用户']);
        }
        if($g['g_status'] != 1){
            return json_encode(['status'=>0,'msg'=>'此群已解散']);
        }
        $same = array_intersect($uids,$uid);
        if($same){
            return json_encode(['status'=>0,'msg'=>'有相同成员']);
        }
        $all = array_merge($uids,$uid);
        if(count($all) >= 500){
            return json_encode(['status'=>0,'msg'=>'成员已满']);
        }
        Db::startTrans();
        try {
            $uidstr = '';
            foreach ($uid as $v) {
                $uidstr .= "userId={$v}&";
            }

            $res = $this->joinin($uidstr,$groupid,$g['g_name']);

            if ($res['code'] != 200) {
                $status = 0;
                $msg = '失败';
            }else{
                $ids = implode($uid,',');
                $newids = ',' . $g['g_uids'] . ',' . $ids . ',';
                Db::table('ew_group')->where('g_id', $groupid)->update(['g_uids'=>$newids]);
                $status = 200;
                $msg = '成功';
            }
            Db::commit();
            $returnData['status'] = $status;
            $returnData['msg'] = $msg;
            return json_encode($returnData);
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $returnData['status'] = 0;
            $returnData['msg'] = "加入失败！";
            return json_encode($returnData);
        }
    }
    /**
     * 退出群组：踢人（暂定：如果群主退出，则解散）
     * 参数：1、uid(必须是数组：退出的这个人的id或者是被踢的这些人的id)，2、groupid(群组id)
     * @return string
     */
    public function outGroup(){
        extract(input());

        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
//        ---------------------------

        $g = Db::table('ew_group')->where('g_id', $groupid)->find();
        $g['g_uids'] = trim($g['g_uids'],',');
        $uids = explode(',',$g['g_uids']);
//        ---------------------------

        $uid = json_decode($uid,true);
        if(!$uid){
            return json_encode(['status'=>0,'msg'=>'请选择用户']);
        }

        $o = count($uid)+1;
        $t = count($uids);
        if(in_array($user_id,$uid) || $o>=$t){
            $res = $this->kill($user_id,$groupid);
            if ($res['code'] != 200) {
                return json_encode(['status'=>0,'msg'=>'解散失败']);
            }else{
                $res = Db::table('ew_group')->where('g_id', $groupid)->update(['g_status'=>2]);
                return json_encode(['status'=>200,'msg'=>'解散成功']);
            }
        }else{
            Db::startTrans();
            try {
                $uidstr = '';
                foreach ($uid as $v) {
                    $uidstr .= "userId={$v}&";
                }
                $res = $this->getout($uidstr,$groupid);
                if ($res['code'] != 200) {
                    $status = 0;
                    $msg = '失败';
                }else{
                    $difids = array_diff($uids,$uid);
                    $ids = implode($difids,',');
                    $newids = ',' . $ids . ',';
                    Db::table('ew_group')->where('g_id', $groupid)->update(['g_uids'=>$newids]);
                    $status = 200;
                    $msg = '成功';
                }
                Db::commit();
                $returnData['status'] = $status;
                $returnData['msg'] = $msg;
                return json_encode($returnData);
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $returnData['status'] = 0;
                $returnData['msg'] = "失败！";
                return json_encode($returnData);
            }
        }

    }

    /**
     * 解散：群主解散或群主退出，都视为解散）
     * 传参：1、groupid(群组id)
     * @return string
     */
    public function killGroup(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = $this->kill($user_id,$groupid);
        if ($res['code'] != 200) {
            return json_encode(['status'=>0,'msg'=>'解散失败']);
        }else{
            Db::table('ew_group')->where('g_id', $groupid)->update(['g_status'=>2]);
            return json_encode(['status'=>200,'msg'=>'解散成功']);
//            $res = Db::table('ew_group')->where('g_id', $groupid)->delete();
//            if($res){
//                return json_encode(['status'=>200,'msg'=>'解散成功']);
//            }else{
//                return json_encode(['status'=>0,'msg'=>'解散失败']);
//            }
        }
    }
    /**
     * 我的群聊
     *
     * @return string
     */
    public function myGroup(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $uid = ',' . $user_id . ',';
        $res = Db::table('ew_group')
            ->where('g_uids', 'like',"%$uid%")
            ->where('g_status', 1)
            ->limit(($pageNum-1)*10,15)
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 我的某个群聊详情
     *
     * @return string
     */
    public function myGroupInfo(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('ew_group')
            ->where('g_id', $groupid)
            ->find();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    public function myGroupUsers(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('ew_group')
            ->where('g_id', $groupid)
            ->find();
        $uids = trim($res['g_uids'],',');
        $users = Db::table('ew_u_user')->where('user_id','in',$uids)
            ->field('user_id,user_username,user_image')->select();
        $res['users'] = $users;
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 修改我的群聊
     *
     * @return string
     */
    public function updateGroup(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = array();
        if(isset($name) && $name){
            $data['g_name'] = $name;
        }
        if(isset($thumb) && $thumb){
            $data['g_thumb'] = $thumb;
        }
        if(isset($notice) && $notice){
            $data['g_notice'] = $notice;
        }
        $res = Db::table('ew_group')->where('g_id', $groupid)
            ->update($data);
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'失败']);
        }

    }
    /**
     * 我还在不在这个群了
     *
     * @return string
     */
    public function whereami(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }

        $status = Db::table('ew_group')
            ->where('g_id', $groupid)
            ->where('g_uids', 'like',"%$user_id%")
            ->find();
        $res = Db::table('ew_group')
            ->where('g_id', $groupid)
            ->find();
        if($status){
            $res['status'] = 1;//我还在
        }else{
            $res['status'] = 0;//我不在了
        }
        $uids = trim($res['g_uids'],',');
        $users = Db::table('ew_u_user')->where('user_id','in',$uids)
            ->field('user_id,user_username,user_image')->select();
        $res['users'] = $users;
        return json_encode(['status'=>200,'msg'=>$res]);

    }




}